package com.xxl.job.executor.service.utils;

import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Random;

public class ApiUtils {
    //生成令牌
    public static String ClientGetCiphertext(String userCode) throws Exception {
        int Tick = ((new Date().getDay() - 1) * 288 + (new Date().getHours() - 1) * 12 + (new Date().getMinutes() / 5));
        String Ciphertext = GetMD5Code(userCode + String.valueOf(Tick)).toUpperCase();
        Random R1 = new Random();
        int i = R1.nextInt(Ciphertext.length() - 6);
        return Ciphertext.substring(i, i + 6).toUpperCase();
    }

    // MD5加密
    private static String GetMD5Code(String InputString) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(InputString.getBytes());
        byte b[] = md.digest();
        int i;
        StringBuffer buf = new StringBuffer("");
        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0) {
                i += 256;
            }
            if (i < 16) {
                buf.append("0");
            }
            buf.append(Integer.toHexString(i));
        }
        String OutputString = buf.toString();
        return OutputString;
    }

    public static String ConvertImageToBase64(File file) throws IOException {
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }
}
